
#include "taskrequest.h"
#include "log.h"
#include "components/attachment.h"

namespace Wishmaster
{
	TaskRequest::TaskRequest(RequestType type, const QUrl& link, const QString& msg, Connector* connector) : Task(msg),
		m_type(type), m_link(link), m_connector(connector)
	{

	}

	TaskRequest::~TaskRequest()
	{
	}

	TaskRequest::RequestType TaskRequest::requestType() const
	{
		return m_type;
	}

	QUrl TaskRequest::link() const
	{
		return m_link;
	}

	void TaskRequest::start()
	{
		if(!m_connector)
			return;
		QString path = link().path();
		if(link().hasQuery())
		{
			path += "?";
			path += QString(link().encodedQuery());
		}
		m_request = m_connector->makeRequest(link().host(), path);
		m_connector->connectRequest(this, SLOT(slot_result(RequestPtr, QByteArray const&)),
									SLOT(slot_progress(int, int)), m_request);
		m_connector->queue(m_request);
		Task::start();
	}

	void TaskRequest::cancel()
	{
		m_request->cancel();
		Task::cancel();
	}

	void TaskRequest::slot_result(const RequestPtr& /*request*/, const QByteArray& /*arr*/)
	{
		emit done(id());
	}

	void TaskRequest::slot_progress(int done, int total)
	{
		//log(llDebug, "pr: %d/%d", done, total);
		setPercentage((double)done / total * 100.);
		emit progress(id(), done, total);
	}
}

